package com.example.bluetoothapplication;

import android.bluetooth.BluetoothA2dp;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothProfile;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import androidx.appcompat.app.AppCompatActivity;

import com.coszero.utilslibrary.utils.LogX;
import com.coszero.utilslibrary.utils.ToastUtils;
import com.example.bluetoothapplication.bluetooth.BluetoothUtils;
import com.example.bluetoothapplication.bluetooth.DeviceConnector;
import com.example.bluetoothapplication.bluetooth.DeviceData;

import java.util.List;

public class MainActivity extends AppCompatActivity {

    private BluetoothProfile mBluetoothProfile;
    private final int INPUT_DEVICE = 0;
    private DeviceConnector connector;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ToastUtils.init(this.getApplication());
        PermissionRequestUtils.requestEasyPermissions(this);
        onClick();
        init();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        BluetoothUtils.getInstance().unregisterReceiver(this);
    }

    private void init() {
        BluetoothUtils.getInstance().init();
        BluetoothUtils.getInstance().openBluetooth(this);
        /*BluetoothUtils.getInstance().registerBoradcastReceiver(this, new BluetoothListener() {
            @Override
            public void bluetoothList(List<BluetoothDevice> deviceList) {
                for (int i = 0; i < deviceList.size(); i++) {
                    BluetoothDevice bluetoothDevice = deviceList.get(i);
                    if ("小米蓝牙语音遥控器".equals(bluetoothDevice.getName())){
                        //停止扫描
                        BluetoothUtils.getInstance().disconnectBluetooth();

                        ToastUtils.showMsg("已搜索到指定蓝牙，开始进行连接");
                        setupConnector(bluetoothDevice);

                        break;
                    }
                }
            }

            @Override
            public void connection(boolean status) {

            }
        });*/

        try {
            BluetoothUtils.getInstance().getAdapter().getProfileProxy(this,
                    mListener, INPUT_DEVICE);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void onClick() {
        findViewById(R.id.btn_search).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                BluetoothUtils.getInstance().doDiscovery();
            }
        });
        findViewById(R.id.btn_link).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                BluetoothUtils.getInstance().getAdapter().cancelDiscovery();
            }
        });

        //判断指定蓝牙是否已连接
        findViewById(R.id.btn_check_connect).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkConnect();
            }
        });
    }

    /**
     * 这里好像只能检查已连接的,运动手环这种已配对就可以使用的检查不到
     */
    private void checkConnect() {
        final BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        BluetoothProfile.ServiceListener mProfileListener = new BluetoothProfile.ServiceListener() {
            public void onServiceConnected(int profile, BluetoothProfile proxy) {
                if (profile == BluetoothProfile.A2DP) {
                    boolean deviceConnected = false;
                    BluetoothA2dp btA2dp = (BluetoothA2dp) proxy;
                    List<BluetoothDevice> a2dpConnectedDevices = btA2dp.getConnectedDevices();
                    if (a2dpConnectedDevices.size() != 0) {
                        for (BluetoothDevice device : a2dpConnectedDevices) {
                            LogX.d("checkConnect", "检查的蓝牙名称:" + device.getName());
                            if (device.getName().contains("DEVICE_NAME")) {
                                deviceConnected = true;
                            }
                        }
                    }
                    if (!deviceConnected) {
                        LogX.d("checkConnect", "指定设备未连接蓝牙");
                    }
                    mBluetoothAdapter.closeProfileProxy(BluetoothProfile.A2DP, btA2dp);
                }
            }

            public void onServiceDisconnected(int profile) {
                // TODO
            }
        };
        mBluetoothAdapter.getProfileProxy(this, mProfileListener, BluetoothProfile.A2DP);
    }


    private BluetoothProfile.ServiceListener mListener = new BluetoothProfile.ServiceListener() {
        @Override
        public void onServiceConnected(int profile, BluetoothProfile proxy) {
            Log.i("bluetooth", "mConnectListener onServiceConnected");
            //BluetoothProfile proxy这个已经是BluetoothInputDevice类型了
            try {
                if (profile == INPUT_DEVICE) {
                    mBluetoothProfile = proxy;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onServiceDisconnected(int profile) {
            Log.i("bluetooth", "mConnectListener onServiceConnected");
        }
    };

    private void setupConnector(BluetoothDevice connectedDevice) {
//        stopConnection();
        try {
            String emptyName = "<New Device>";
            DeviceData data = new DeviceData(connectedDevice, emptyName);
            connector = new DeviceConnector(data, BluetoothUtils.getInstance().getmHandler());
            connector.connect();
        } catch (IllegalArgumentException e) {
            LogX.e("setupConnector failed: " + e.getMessage());
        }
    }
}